package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.anno.RpcProvider;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @description:
 * @author: yx
 * @date: 2022/1/17 11:20
 */
@Component
public class MyBeanProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            RpcProvider rpcProvider = field.getAnnotation(RpcProvider.class);
            if (rpcProvider != null) {
                Object proxy = RpcClientProxy.createProxy(field.getType());
                try {
                    field.setAccessible(true);
                    field.set(bean, proxy);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
